<template>
  <div class="flex flex-col mt-1 overflow-hidden">
    <a-radio-group v-model:value="store.categroyType" button-style="solid" class="flex radio-style" @change="getTree">
      <a-radio-button value="0">门诊病历</a-radio-button>
      <a-radio-button value="1">住院病历</a-radio-button>
      <a-radio-button value="2">护理文书</a-radio-button>
      <a-radio-button value="3">检查报告</a-radio-button>
      <a-radio-button value="4">手术文书</a-radio-button>
    </a-radio-group>
    <a-input-search v-model:value="searchKey" placeholder="病历名称/助记码" class="mt-2" @search="getTree" />
    <a-spin :spinning="loading" class="h-full" wrapper-class-name="h-full">
      <a-directory-tree
        v-if="treeData.length"
        v-model:selected-keys="selectedKeys"
        default-expand-all
        :tree-data="treeData"
        class="h-full overflow-hidden overflow-x-auto"
        :field-names="{
          key: 'treeId'
        }"
        @select="onSelectTemplate"
      >
        <template #icon="{ template }">
          <img v-if="template" :src="IconDocument" width="14" class="pb-1" />
          <img v-else :src="IconDirectory" width="14" class="pb-1" />
        </template>
        <template #title="item">
          <div class="inline-flex justify-between items-center w-full">
            <div v-if="item.template" class="mr-2 truncate w-40" :title="item.templateName">{{ item.templateName }}</div>
            <div v-else class="mr-4 truncate w-40" :title="item.categoryName">{{ item.categoryName }}</div>
            <div v-if="haveAdd" class="flex items-center">
              <template v-if="item.template">
                <div class="w-16 flex justify-around text-gray-400 text-xs">
                  <span class="mr-1">{{ ['复', '初', '不限'][+item.isFirst] }}</span>
                  <span>{{ ['不限', '男', '女'][+item.sexRange] }}</span>
                </div>
                <div class="ml-2">
                  <a-dropdown placement="bottomLeft" :disabled="item.templateStatus === '1'">
                    <template #overlay>
                      <a-menu class="text-center">
                        <a-menu-item>
                          <BaseButton size="small" type="link" @click="onAddTemplate(item)"> 修改 </BaseButton>
                        </a-menu-item>
                        <a-menu-item>
                          <BaseButton danger size="small" type="link" confirm-text="确定删除模版?" @click="onDeleteTemplate(item)">删除</BaseButton>
                        </a-menu-item>
                      </a-menu>
                    </template>
                    <a-button type="text" :icon="h(MoreOutlined)" size="small" />
                  </a-dropdown>
                </div>
              </template>
              <a-space v-else>
                <a-button type="text" :icon="h(FormOutlined)" size="small" @click.stop="onAddDirectory(item)" />
                <!-- <a-button type="text" danger :icon="h(CloseOutlined)" size="small" @click.stop="onDeleteDrectory(id)" /> -->
                <BaseButton size="small" type="text" danger :icon="h(CloseOutlined)" confirm-text="确定删除该目录?" @click="onDeleteDrectory(item)" />
                <a-button type="text" :icon="h(PlusOutlined)" size="small" @click.stop="onAddTemplate(item, true)" />
              </a-space>
            </div>
          </div>
        </template>
      </a-directory-tree>
      <a-empty v-else class="w-full h-full" />
      <BaseButton v-if="haveAdd" class="mt-4" type="primary" block ghost :icon="h(PlusOutlined)" @click="onAddDirectory()"> 新增病历文书目录 </BaseButton>
      <AddDirectory v-model:open="openDirectory" :row-data="directoryRowData" @success="getTree" />
      <AddTemplate v-model:open="openTemplate" :row-data="templateRowData" @success="onAddSuccess" />
    </a-spin>
  </div>
</template>

<script setup>
import { ref, h, onMounted } from 'vue'
import { FormOutlined, PlusOutlined, MoreOutlined, CloseOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import IconDirectory from '@/assets/icons/icon-directory.svg'
import IconDocument from '@/assets/icons/icon-document.svg'
import useStore from '../store'
import AddDirectory from './AddDirectory.vue'
import AddTemplate from './AddTemplate.vue'

const props = defineProps({
  haveAdd: {
    type: Boolean,
    default: false
  },
  emrLoading: {
    type: Boolean,
    default: true
  }
})
const emit = defineEmits(['select', 'refresh'])
const store = useStore()

const loading = ref(true)
const openDirectory = ref(false)
const openTemplate = ref(false)

const searchKey = ref('')
const treeData = ref([])
const selectedKeys = ref([])
const templateRowData = ref({})
const directoryRowData = ref({})
const onAddSuccess = async () => {
  await getTree()
  setTimeout(() => {
    emit('refresh')
  }, 100)
}
// 获取文书
const getTree = async () => {
  // treeData.value = []
  loading.value = true
  const { code, data, msg } = await post('/emr/emrCategory/getEmrCategoryByTree', {
    categroyType: store.categroyType,
    zjm: searchKey.value
  })
  loading.value = false
  if (code !== 0) return message.error(msg)
  treeData.value = data
  addLevelFieldRecursive(treeData.value)
  store.templateId && (selectedKeys.value = [store.templateId])
}
// 新增病历文书
const onAddDirectory = (row) => {
  openDirectory.value = true
  directoryRowData.value = row ? row : {}
}

// 新增模版
const onAddTemplate = (row, isAdd = false) => {
  openTemplate.value = true
  if (isAdd) {
    templateRowData.value = {
      id: '',
      categoryName: row.categoryName,
      categroyId: row.id
    }
  } else {
    templateRowData.value = { ...row }
  }
}

// 删除目录
const onDeleteDrectory = async (row) => {
  const { code, msg } = await post('/emr/emrCategory/doDelEmrCategory/' + row.id)
  if (code !== 0) return message.error(msg)
  message.success('删除成功')
  getTree()
}
// 删除模版
const onDeleteTemplate = async (row) => {
  const { code, msg } = await post('/emr/emrTemplate/doDelEmrTemplete/' + row.templateId)
  if (code !== 0) return message.error(msg)
  message.success('删除成功')
  getTree()
}

// 点击模版
const onSelectTemplate = (_, e) => {
  if (props.emrLoading) {
    selectedKeys.value = []
    return message.warning('电子病历加载中，请稍后')
  }
  const row = e.node
  if (row.templateId) {
    store.templateId = row.templateId
    store.templateInfo = row
    emit('select')
  } else {
    store.templateId = ''
    store.templateInfo = {}
    emit('select')
  }
}
function addLevelFieldRecursive(treeData, level = 1) {
  treeData.forEach((node) => {
    node.level = level // 添加层级字段
    if (node.children?.length > 0) {
      addLevelFieldRecursive(node.children, level + 1) // 递归处理子节点
    }
  })
}
watch(
  () => store.templateId,
  (val) => {
    if (val) {
      selectedKeys.value = [val]
    }
  }
)
onMounted(() => {
  getTree()
})
defineExpose({
  getData: getTree
})
</script>
<style lang="less" scoped>
.icon-color {
  color: var(--primary-color);
}
:deep(.ant-spin-container) {
  display: flex;
  flex-direction: column;
  height: 100%;
}
:deep(.ant-tree) {
  .ant-tree-list {
    height: 100%;
    overflow: auto;
  }
  .ant-tree-switcher {
    width: 16px !important;
  }
}
:deep(.ant-tree-indent-unit) {
  width: 16px !important;
}
:deep(.ant-tree-treenode) {
  display: flex;
  width: 100%;
  padding: 8px 0;
  button:not(.ant-btn-dangerous) {
    color: var(--primary-color);
  }
  .ant-tree-node-selected {
    button:not(.ant-btn-dangerous) {
      color: #fff;
    }
  }

  &:before {
    bottom: 0 !important;
  }
  .ant-tree-node-content-wrapper {
    display: flex;
    align-items: center;
    .ant-tree-title {
      flex: 1;
    }
  }
}
.radio-style {
  display: flex;
  :deep(.ant-radio-button-wrapper) {
    // width: 33.3%;
    flex: 1;
    padding: 0;
    text-align: center;
  }
}
</style>
